/*
 * @Description: 工具库函数
 *  
 * @Date: 2021-03-02 10:42:00
 */

class Units {
	isDate(value) {
		return Object.prototype.toString.call(value) === '[object Date]'
	}
	isArray(value) {
		return Object.prototype.toString.call(value) === '[object Array]'
	}
	isReg(value) {
		return Object.prototype.toString.call(value) === '[object RegExp]'
	}
	isFun(value) {
		return Object.prototype.toString.call(value) === '[object Function]'
	}
	isObeject(value) {
		return Object.prototype.toString.call(value) === '[object Object]'
	}
	isString(value) {
		return Object.prototype.toString.call(value) === '[object String]'
	}
	// 是否是微信环境
	isWechat() {
		return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
	}
	// 取[begin, end]间的数据整数
	GetRandom(begin, end) {
		var num = Math.random() * 100000000
		return Math.floor((num % (end - begin + 1)) + begin)
	}
	// 取len长的随机字符串
	GetRandString(len, range) {
		range = range || '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
		var s = range.split('')
		var ret = ''
		for (var i = 0; i < len; i++) {
			ret += s[this.GetRandom(0, s.length - 1)]
		}
		return ret
	}
	// 取时间戳(秒)
	GetTimestamp(timestr) {
		var t
		if (timestr) {
			t = new Date(timestr)
		} else {
			t = new Date()
		}
		return parseInt(t.getTime() / 1000)
	}
	// 解析地址栏url参数
	parseURL(url) {
		var a = document.createElement('a')
		a.href = url
		return {
			source: url,
			protocol: a.protocol.replace(':', ''),
			host: a.hostname,
			port: a.port || '80',
			query: a.search,
			params: (function () {
				var ret = {},
					seg = a.search.replace(/^\?/, '').split('&'),
					len = seg.length,
					i = 0,
					s
				for (; i < len; i++) {
					if (!seg[i]) {
						continue
					}
					s = seg[i].split('=')
					ret[s[0]] = s[1]
				}
				return ret
			})(),
			file: (a.pathname.match(/\/([^/?#]+)$/i) || ['', ''])[1],
			hash: a.hash.replace('#', ''),
			path: a.pathname.replace(/^([^/])/, '/$1'),
			relative: (a.href.match(/tps?:\/\/[^/]+(.+)/) || ['', ''])[1],
			segments: a.pathname.replace(/^\//, '').split('/'),
		}
	}
	//把数字 转成汉字数字
	toChineseNum(num) {
		const keys = [
			'零',
			'一',
			'二',
			'三',
			'四',
			'五',
			'六',
			'七',
			'八',
			'九',
			'十',
			'十一',
			'十二',
			'十三',
			'十四',
			'十五',
			'十六',
			'十七',
			'十八',
			'十九',
			'二十',
		]
		return keys[Number(num)]
	}
	// 用于遍历数组和对象元素
	each(o, callback = () => false) {
		// 如果是对象
		if (this.isObeject(o) || this.isArray(o)) {
			for (let i in o) {
				if (callback(o[i], i, o) === false) {
					return
				}
			}
		}
		// 如果是数组
		if (this.isArray(o)) {
			for (let i = 0; i < o.length; i++) {
				if (callback(o[i], i, o) === false) {
					return
				}
			}
		}
	}
	// 深度克隆 对象
	deepClone(v, o = v) {
		if (this.isDate(v)) {
			o = new Date(v.getTime())
		}
		this.isObeject(v) && (o = {})
		this.isArray(v) && (o = [])
		if (this.isObeject(v) || this.isArray(v)) {
			for (let key in v) {
				o[key] = this.deepClone(v[key])
			}
		}
		return o
	}
	// 获取id
	getUuid() {
		this.uuid = this.uuid || (this.uuid = 0)
		return ++this.uuid + this.GetRandString(5)
	}
	// 去空格
	trimSpace(val) {
		let reg = /^\s+|\s+$/g
		return val.replace(reg, '')
	}
	// 去除空对象数据
	deleteEmpty(data) {
		for (var key in data) {
			if (data[key] === '' || data[key] === undefined || data[key] === null) {
				delete data[key]
			}
		}
	}
	// 是否是空数据
	isEmpty(data) {
		return [undefined, '', null, NaN].includes(data)
	}
	// 布尔类型 转换成数字
	boolChangeNum(data) {
		if (this.isEmpty(data)) {
			return data
		}
		return data ? 1 : 0
	}
	// 单位拼接
	joinUnit(val, u) {
		if (!val || !u) {
			return val
		}
		return val + u
	}
	// 保留2位小数补0
	toDecimal2(x, decimal = 2) {
		let times = Math.pow(10, decimal)
		var f = parseFloat(x)
		if (isNaN(f)) {
			return x
		}
		f = Math.floor(x * times) / times
		var s = f.toString()
		var rs = s.indexOf('.')
		if (rs < 0) {
			rs = s.length
			s += '.'
		}
		while (s.length <= rs + decimal) {
			s += '0'
		}
		return s
	}
	saveFloorDecimal(x, s = 2) {
		let times = Math.pow(10, s)
		var f = parseFloat(x)
		if (isNaN(f)) {
			return x
		}
		return Math.floor(x * times) / times
	}
}
/**
 * 节流函数，对多次触发的函数，单位时间内只执行一次
 * @param {Function} fun 需被节流的函数
 * @param {Number} delay 单位时间
 */
var unit = new Units()
export default unit
/**
 * 节流函数，对多次触发的函数，单位时间内只执行一次
 * @param {Function} fun 需被节流的函数
 * @param {Number} delay 单位时间
 */
export function throttle(fun, delay) {
	let last, deferTimer
	return function () {
		let that = this
		let _args = arguments
		let now = +new Date()
		if (last && now < last + delay) {
			clearTimeout(deferTimer)
			deferTimer = setTimeout(function () {
				last = now
				fun.apply(that, _args)
			}, delay)
		} else {
			last = now
			fun.apply(that, _args)
		}
	}
}

/**
 * 防抖函数，对多次触发的函数，只执行最后一次
 * @param {Function} fun 需被防抖的函数
 * @param {Number} delay 单位时间
 */
export function debounce(fun, delay) {
	return function (args) {
		let that = this
		clearTimeout(fun.id)
		fun.id = setTimeout(function () {
			fun.call(that, args)
		}, delay)
	}
}

// 生成uuid
// len: 长度
// radix: 基数
export function uuid(len, radix) {
	var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
	var uuid = []
	let i
	radix = radix || chars.length
	if (len) {
		for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
	} else {
		var r
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
		uuid[14] = '4'
		for (i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = 0 | (Math.random() * 16)
				uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]
			}
		}
	}
	return uuid.join('')
}
// 异步加载图片
export async function getImageObject(src, v = 123) {
	return new Promise((resolve, reject) => {
		let image = new Image()
		image.setAttribute('crossorigin', 'anonymous')
		image.src = src + `?v=${v}`
		image.onload = function () {
			resolve(image)
		}
		image.onerror = function (e) {
			console.log('图片加载错误=>', e)
			reject()
		}
	})
}
// 对象转表单
export function objTransformForm(obj) {
	if (typeof obj !== 'object') {
		return ''
	}
	let str = ''
	Object.keys(obj).forEach((key) => {
		let temp = `${key}=${obj[key]}&`
		str += temp
	})
	return str.slice(0, str.length - 1)
}

/* 时间转字符串 */
export function dateToString(value, type = 'yyyy-mm-dd hh:mm:ss') {
	if (!value || value === undefined || !(value instanceof Date)) {
		return ''
	}
	const map = {
		'yyyy-mm-dd hh-mm-ss': `${value.getFullYear()}-${value.getMonth() +
			1}-${value.getDate()} ${value.getHours()}-${value.getMinutes()}-${value.getSeconds()}`.replace(/\b(\w)\b/g, '0$1'),
		'yyyy-mm-dd hh:mm:ss': `${value.getFullYear()}-${value.getMonth() +
			1}-${value.getDate()} ${value.getHours()}:${value.getMinutes()}:${value.getSeconds()}`.replace(/\b(\w)\b/g, '0$1'),
		'yyyy-mm-dd hh:mm': `${value.getFullYear()}-${value.getMonth() + 1}-${value.getDate()} ${value.getHours()}:${value.getMinutes()}`.replace(
			/\b(\w)\b/g,
			'0$1'
		),
		'yyyy-mm-dd': `${value.getFullYear()}-${value.getMonth() + 1}-${value.getDate()}`.replace(/\b(\w)\b/g, '0$1'),
		'hh:mm:ss': `${value.getHours()}:${value.getMinutes()}:${value.getSeconds()}`.replace(/\b(\w)\b/g, '0$1'),
		'hh:mm': `${value.getHours()}:${value.getMinutes()}`.replace(/\b(\w)\b/g, '0$1'),
		'yyyy mm dd': `${value.getFullYear()} ${value.getMonth() + 1} ${value.getDate()}`.replace(/\b(\w)\b/g, '0$1'),
		'yyyy-mm': `${value.getFullYear()}-${value.getMonth() + 1}`.replace(/\b(\w)\b/g, '0$1'),
		yyyy: `${value.getFullYear()}}}`.replace(/\b(\w)\b/g, '0$1'),
		month: `${value.getMonth() + 1}}`.replace(/\b(\w)\b/g, '0$1'),
		mm: `${value.getMinutes()}`.replace(/\b(\w)\b/g, '0$1'),
		ss: `${value.getSeconds()}`.replace(/\b(\w)\b/g, '0$1'),
	}
	return map[type]
}

// 从一个对象中获取本对象需要的值
// 把originObj 赋值给 curretObj对象
export function getAssignPlain(curretObj, originObj) {
	Object.keys(curretObj).forEach((key) => {
		![undefined, '', null, NaN].includes(originObj[key]) && (curretObj[key] = originObj[key])
	})
}

// 递归删除空的子选项
export function deleteEmptyChild(list, option = {}) {
	list.forEach((item) => {
		if (item.childrens && !item.childrens.length) {
			delete item.childrens
		}
		if (item.childrens && item.childrens.length) {
			deleteEmptyChild(item.childrens)
		}
	})
}
/**把树结构处理成平级机构 */
export function handleTreeLevel(treeData, arr = []) {
	for (const element of treeData) {
		let elem = element
		arr.push(elem)
		if (elem.childrens && elem.childrens.length) {
			handleTreeLevel(elem.childrens, arr)
		}
	}
	return arr
}

export function pushZero(str, len = 10) {
	let handStr = String(str)
	if (!Number(handStr) || handStr.length >= len) {
		return str
	}
	let i = len - handStr.length
	while (i > 0) {
		handStr = '0' + handStr
		i--
	}
	return handStr
}
// 门店截取零
export function deleteZero(str, len = 6) {
	if (!Number(str) || str.length <= len) {
		return str
	}
	return str.slice(-6)
}
// 获取当前年月时间
export function getCurrentMonth() {
	let value = new Date()
	let startTime = `${value.getFullYear()}-${value.getMonth() + 1}-01 00:00:00`
	let endTime = `${value.getFullYear()}-${value.getMonth() + 1}-${value.getDate()} ${value.getHours()}:${value.getMinutes()}:${value.getSeconds()}`
	console.log('获取当前时间=>', startTime, endTime)
	return [new Date(startTime), new Date(endTime)]
}
export function formatMoney(number, places, symbol, thousand, decimal) {
	number = number || 0
	places = Math.abs(places)
	places = !isNaN(places) ? places : 2
	symbol = symbol !== undefined ? symbol : '$'
	thousand = thousand || ','
	decimal = decimal || '.'
	var negative = number < 0 ? '-' : ''
	number = Math.abs(+number || 0).toFixed(places)
	var i = parseInt(number, 10) + ''
	var j = (j = i.length) > 3 ? j % 3 : 0
	return (
		symbol +
		negative +
		(j ? i.substr(0, j) + thousand : '') +
		i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousand) +
		(places
			? decimal +
			Math.abs(number - i)
				.toFixed(places)
				.slice(2)
			: '')
	)
}
// 去除对象里的
function isArray(value) {
	return Object.prototype.toString.call(value) === '[object Array]'
}
function isObeject(value) {
	return Object.prototype.toString.call(value) === '[object Object]'
}
export function removeDataEmpty(obj) {
	// 是否是数组
	if (isArray(obj)) {
		obj.forEach((elem, i) => {
			if (elem === null || (isObeject(elem) && !Object.keys(obj).length)) {
				obj.splice(i, 1)
				return
			}
			removeDataEmpty(elem)
		})
		return
	}
	// 是否是对象
	if (isObeject(obj) && Object.keys(obj).length) {
		Object.keys(obj).forEach((key) => {
			if (obj[key] === null) {
				delete obj[key]
				return
			}
			removeDataEmpty(obj[key])
		})
	}
	return obj
}

// 判断是否是时间段内
export function isDuringDateOneDay(beginDateStr, endDateStr) {
	var curDate = new Date(),
		curDateStr = `${curDate.getFullYear()}-${curDate.getMonth() + 1}-${curDate.getDate()}`.replace(/\b(\w)\b/g, '0$1'),
		beginDate = new Date(curDateStr + ' ' + beginDateStr),
		endDate = new Date(curDateStr + ' ' + endDateStr)
	console.log('判断当前时间=>', { curDate: dateToString(curDate), beginDate: dateToString(beginDate), endDate: dateToString(endDate) })
	return curDate >= beginDate && curDate <= endDate
}


function arrayToTree(arr, colParentId = null) {
	const tree = [];
	for (let i = 0; i < arr.length; i++) {
		if (arr[i].colParentId === colParentId) {
			const node = {
				...arr[i],
				children: arrayToTree(arr, arr[i].colId)
			};
			tree.push(node);
		}
	}
	return tree;
}
export function handleArryToTree(arr, colParentId) {
	return arrayToTree(arr, colParentId)
}



// element-input 验证手机号
const validateMobile = function (rule, value, callback) {
	let newValue = value.replace(/[^0-9]/gi, '')
	if (value !== newValue) {
		callback(new Error('请输入正确的手机号'))
	} else if (newValue.length !== 11) {
		callback(new Error('请输入正确的手机号'))
	} else {
		callback()
	}
}
export { validateMobile }

/**
 * 验证邮箱
 * @params:rule
 */
const validateEmail = (rule, value, callback) => {
	//验证邮箱的正则
	const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
	if (regEmail.test(value)) {
		//合法邮箱
		return callback()
	}
	callback(new Error('请输入合法的邮箱'))
}
export { validateEmail }
